package gentle.service.impl;

import com.alibaba.fastjson.JSONObject;
import gentle.base.AliyunOssUtil;
import gentle.base.SqlMapper;
import gentle.base.StringUtil;
import gentle.entity.ExtenAccountInfo;
import gentle.entity.ReservationsCallInInfo;
import gentle.entity.ReservationsCallsOutInfo;
import gentle.mapper.ReservationsDao;
import gentle.service.IOnlineConsultationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.io.File;
import java.io.OutputStream;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.IOException;
import java.io.FileInputStream;

/**
 * @author py
 * @Date 2019年4月19日23:15:54
 */
@Service
public class OnlineConsultationServiceImpl implements IOnlineConsultationService {
    @Autowired
    private ReservationsDao reservationsDao;

    @Autowired
    private SqlMapper sqlMapper;

    @Autowired
    AliyunOssUtil aliyunOssUtil;

    public void wh() {
//        aliyunOssUtil.pushSingleFile(getMulFileByPath("D:\\UCVoice\\RecordFile\\[2020-08-26]\\18602744611-600000-20200826214000.wav"), "wh/18602744611-600000-20200826214000.wav");
        try {
            String result = "";
            ReservationsCallsOutInfo reservationsCallsOutInfo = reservationsDao.getMaxWhTime();
            System.out.println(reservationsCallsOutInfo.getEndTimes().replace(" ", "%20"));
            String urlNameString = "http://192.168.0.210:8860/HttpAPI.aspx?op=outlist&BeginTime=" + reservationsCallsOutInfo.getEndTimes().replace(" ", "%20") + "";
//            urlNameStringr = "http://118.31.106.241:8860/HttpAPI.aspx?op=inlist&BeginTime=2020/9/13%2020:34:18";
            System.out.println("22222211" + urlNameString);
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            if (result == null || "".equals(result)) {

            } else {
                String[] aa = result.substring(0, result.length() - 1).split("},");
                int isexistfile = 0;
                if (aa.length > 0) {
                    for (String s : aa) {
                        s = (s + "}").replace("\\", "/");
                        JSONObject jo = JSONObject.parseObject(new String(s));
                        Map<String, Object> params = new HashMap<String, Object>();
                        if (StringUtil.isNotEmpty(jo.getString("WorkerID"))) {
                            params.put("exten", jo.getString("WorkerID"));
                        }
                        ExtenAccountInfo extenAccountInfo = reservationsDao.getAccount(params);
                        String account = "6666";
                        String areaAbbreviation = "yiya_";
                        if (extenAccountInfo != null) {
                            account = extenAccountInfo.getAccount();
                            areaAbbreviation = extenAccountInfo.getAreaAbbreviation();
                        }
                        File file = new File(jo.getString("RecFile"));
                        if (file.exists()) {
                            aliyunOssUtil.pushSingleFile(getMulFileByPath(jo.getString("RecFile")), "wh/" + jo.getString("RecFile").split("]/")[1]);
                            isexistfile = 1;
                        } else {
                            isexistfile = 0;
                        }
                       // String BeginTime = "2020/12/11 星期五 上午 11:20:05";
                        String BeginTime = parseDateInfo(jo.getString("BeginTime"));
                        String EndTime = parseDateInfo(jo.getString("EndTime"));
                        System.out.println("strs:"+BeginTime);
                        System.out.println("往reservemoney_call_records插入");
                        String url = "https://pynnn.oss-cn-hangzhou.aliyuncs.com/wh/" + jo.getString("RecFile").split("]/")[1];
                        String insqlwh = "INSERT INTO `reservemoney_call_records` (`n_id`,`name`,`isexistfile`, `flow_no`, `caller_id`, `callee_id`, `begin_time`, `end_time`, `hold`,`rec_file`, `reviewKey`, `worker_id`, `result`, `cus_id`, `flag`, `call_results`, `call_yiXiang`, `content`, `is_syn`, `fax`, `call_hold`,area_abbreviation) VALUES ('" + jo.getString("nID") + "','" + account + "','" + isexistfile + "','" + jo.getString("FlowNo") + "','" + jo.getString("CallerID") + "','" + jo.getString("CalleeID") + "','" + BeginTime + "'" +
                                ",'" + EndTime + "','" + jo.getString("Hold") + "','" + url + "','" + jo.getString("ReviewKey") + "'" +
                                ",'" + jo.getString("WorkerID") + "','" + jo.getString("Result") + "','" + jo.getString("CusID") + "','" + jo.getString("flag") + "','" + jo.getString("CallResults") + "'" +
                                ",'" + jo.getString("CallYiXiang") + "','" + jo.getString("content") + "','" + jo.getString("IsSyn") + "','" + jo.getString("Fax") + "','" + jo.getString("CallHold") + "','yiya_yc_')";
                        sqlMapper.insert(insqlwh);
                        System.out.println("插入");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void hr() {
        try {
            String resultr = "";
            ReservationsCallInInfo reservationsCallInInfo = reservationsDao.getMaxHrTime();
            System.out.println(reservationsCallInInfo.getEndTime().replace(" ", "%20"));
            String urlNameStringr = "http://192.168.0.210:8860/HttpAPI.aspx?op=inlist&BeginTime=" + reservationsCallInInfo.getEndTime().replace(" ", "%20") + "";
//            urlNameStringr = "http://118.31.106.241:8860/HttpAPI.aspx?op=inlist&BeginTime=2020/9/13%2020:34:18";
            URL realUrlr = new URL(urlNameStringr);
            // 打开和URL之间的连接
            URLConnection connectionr = realUrlr.openConnection();
            // 设置通用的请求属性
            connectionr.setRequestProperty("accept", "*/*");
            connectionr.setRequestProperty("connection", "Keep-Alive");
            connectionr.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connectionr.connect();
            // 获取所有响应头字段
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader inr = new BufferedReader(new InputStreamReader(connectionr.getInputStream()));
            String liner;
            while ((liner = inr.readLine()) != null) {
                resultr += liner;
            }
            if (resultr == null || "".equals(resultr)) {

            } else {
                String[] aa = resultr.substring(0, resultr.length() - 1).split("},");
                int isexistfile = 0;
                if (aa.length > 0) {
                    for (String s : aa) {
                        s = (s + "}").replace("\\", "/");
                        JSONObject jo = JSONObject.parseObject(new String(s));
                        Map<String, Object> params = new HashMap<String, Object>();
                        if (StringUtil.isNotEmpty(jo.getString("WorkerID"))) {
                            params.put("exten", jo.getString("WorkerID"));
                        }
                        ExtenAccountInfo extenAccountInfo = reservationsDao.getAccount(params);
                        String account = "8888";
                        String areaAbbreviation = "yiya_";
                        if (extenAccountInfo != null) {
                            account = extenAccountInfo.getAccount();
                            areaAbbreviation = extenAccountInfo.getAreaAbbreviation();
                        }
                        File file = new File(jo.getString("RecFile"));
                        if (file.exists()) {
                            aliyunOssUtil.pushSingleFile(getMulFileByPath(jo.getString("RecFile")), "hr/" + jo.getString("RecFile").split("]/")[1]);
                            isexistfile = 1;
                        } else {
                            isexistfile = 0;
                        }
                        // String BeginTime = "2020/12/11 星期五 上午 11:20:05";
                        String BeginTime = parseDateInfo(jo.getString("BeginTime"));
                        String EndTime = parseDateInfo(jo.getString("EndTime"));
                        System.out.println("strs:"+BeginTime);
                        String url = "https://pynnn.oss-cn-hangzhou.aliyuncs.com/hr/" + jo.getString("RecFile").split("]/")[1];
                        String insql = "INSERT INTO `reservemoney_callin_records` (`n_id`,`name`,`isexistfile`, `flow_no`, `caller_id`, `callee_id`, `begin_time`, `end_time`, `hold`,`rec_file`, `reviewKey`, `worker_id`, `result`, `cus_id`, `flag`, `call_results`, `call_yiXiang`, `content`, `is_syn`, `fax`, `call_hold`,area_abbreviation) VALUES " +
                                "('" + jo.getString("nID") + "','" + account + "','" + isexistfile + "','" + jo.getString("FlowNo") + "','" + jo.getString("CallerID") + "','" + jo.getString("CalleeID") + "','" + BeginTime + "'" +
                                ",'" + EndTime + "','" + jo.getString("Hold") + "','" + url + "','" + jo.getString("ReviewKey") + "'" +
                                ",'" + jo.getString("WorkerID") + "','" + jo.getString("Result") + "','" + jo.getString("CusID") + "','" + jo.getString("flag") + "','" + jo.getString("CallResults") + "'" +
                                ",'" + jo.getString("CallYiXiang") + "','" + jo.getString("content") + "','" + jo.getString("IsSyn") + "','" + jo.getString("Fax") + "','" + jo.getString("CallHold") + "','yiya_yc_')";
                        sqlMapper.insert(insql);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static String parseDateInfo(String baseDate){
        if(baseDate.length() > 20){
            String[] dateArr = baseDate.split(" ");
            String[] yyyymmddArr = dateArr[0].split("\\/");
            String yyyymmddString = yyyymmddArr[0];
            if(yyyymmddArr[1].length() == 1){
                yyyymmddString = yyyymmddString +"-0"+yyyymmddArr[1];
            }else{
                yyyymmddString = yyyymmddString +"-"+yyyymmddArr[1];
            }
            if(yyyymmddArr[2].length() == 1){
                yyyymmddString = yyyymmddString +"-0"+yyyymmddArr[2];
            }else{
                yyyymmddString = yyyymmddString +"-"+yyyymmddArr[2];
            }
            String[] hhmmssArr = dateArr[3].split(":");
            String hhmmssString = "";
            boolean isPm = false;
            if(baseDate.contains("下午")){
                isPm = true;
            }
            int hourNum = Integer.parseInt(hhmmssArr[0]);
            if(isPm){//如果是下午，需要在小时+12
                hourNum = hourNum+12;
                hhmmssArr[0] = hourNum+"";
            }
            if(hhmmssArr[0].length() == 1){
                hhmmssString = "0"+hhmmssArr[0];
            }else{
                hhmmssString = hhmmssArr[0];
            }
            if(hhmmssArr[1].length() == 1){
                hhmmssString = hhmmssString +":0"+hhmmssArr[1];
            }else{
                hhmmssString = hhmmssString +":"+hhmmssArr[1];
            }
            if(hhmmssArr[2].length() == 1){
                hhmmssString = hhmmssString +":0"+hhmmssArr[2];
            }else{
                hhmmssString = hhmmssString +":"+hhmmssArr[2];
            }
            return yyyymmddString+" "+hhmmssString;
        }
        return baseDate;
    }
    public static MultipartFile getMulFileByPath(String picPath) {
        FileItem fileItem = createFileItem(picPath);
        MultipartFile mfile = new CommonsMultipartFile(fileItem);
        return mfile;
    }

    private static FileItem createFileItem(String filePath) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        String textFieldName = "textField";
        int num = filePath.lastIndexOf(".");
        String extFile = filePath.substring(num);
        FileItem item = factory.createItem(textFieldName, "text/plain", true,
                "MyFileName" + extFile);
        File newfile = new File(filePath);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(newfile);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192))
                    != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }
}
